//
//  DFImagePickerController.m
//  换换圈
//
//  Created by 艾柯斯 on 14-12-9.
//  Copyright (c) 2014年 艾柯斯. All rights reserved.
//

#import "DFImagePickerController.h"



typedef void (^CompletionBlock)(UIImage* image,UIImage* srcImage);
typedef void (^CancelBlock)();
typedef void (^NoAvailable)(UIImagePickerControllerSourceType sourceType);

@interface DFImagePickerController()  <UIImagePickerControllerDelegate,UINavigationControllerDelegate>{
    CompletionBlock _completion;
    CancelBlock _cancel;
    NoAvailable _noAvailable;
}

@end

@implementation DFImagePickerController


#pragma mark - image picker delegte
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissViewControllerAnimated:YES completion:nil];
    if(_completion) {
        
        _completion(info[UIImagePickerControllerEditedImage],info[UIImagePickerControllerOriginalImage]);
    }
    
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
    if(_cancel) {
        _cancel();
    }
}


-(void)showInViewController:(UIViewController *)viewController completion:(void (^)(UIImage *, UIImage *))completion cancel:(void (^)())cancel noAvailable:(void (^)(UIImagePickerControllerSourceType))noAvailable {
    _completion = completion;
    _cancel = cancel;
    _noAvailable = noAvailable;
    
    DFActionSheet * actionSheet = [[DFActionSheet alloc] initWithTitle:@"选择图像" delegate:nil cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照", @"从相册选择", nil];
    [actionSheet showInView:viewController.view clickedButton:^(NSInteger buttonIndex) {
        NSUInteger sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        switch (buttonIndex) {
            case 0: //相机
                sourceType = UIImagePickerControllerSourceTypeCamera;
                break;
            case 1: //相册
                sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                break;
            default:
                return;
        }
        
        BOOL available = [UIImagePickerController isSourceTypeAvailable:sourceType];
        if(!available) {
            if(noAvailable) {
                noAvailable(sourceType);
            }
            return;
        }
        
        // 跳转到相机或相册页面
        
        self.delegate = self;
        self.allowsEditing = YES;
        self.sourceType = sourceType;
        [viewController presentViewController:self animated:YES completion:nil];
        
    }];
    
}


-(void)showInViewController:(UIViewController *)viewController completion:(void (^)(UIImage *, UIImage *))completion {
  
    
    
}

@end
